#include <opencv\cv.h>
#include <opencv\highgui.h>


#include "iostream"
#include <fstream>
#include "stdlib.h"
#include <stdint.h>

using namespace cv;

double roadPoint = 0;
double vehiclePoint = 0;

int mainold(){

	waitKey();
	CvCapture *input = cvCaptureFromCAM(0);
	//CvCapture *input = cvCaptureFromFile(
	//	"mv2_001.avi"
	//	);
	if (input == NULL)
	{
		fprintf(stderr, "Error: Can't open video.\n");
		return -1;
	}
	CvSize imgSize;
	imgSize.width = (int) cvGetCaptureProperty( input, CV_CAP_PROP_FRAME_WIDTH );
	imgSize.height = (int) cvGetCaptureProperty( input, CV_CAP_PROP_FRAME_HEIGHT );
	IplImage* greyImage = cvCreateImage(imgSize, IPL_DEPTH_8U, 1);
	IplImage* roadImage = cvCreateImage(imgSize, IPL_DEPTH_8U, 1);
	IplImage* colourImage = NULL;
	IplImage* movingAverage = cvCreateImage(imgSize, IPL_DEPTH_32F, 3);
	IplImage* difference = NULL;
	IplImage* temp = NULL;
	IplImage* motionHistory = cvCreateImage(imgSize, IPL_DEPTH_8U, 3);
	bool first = true;
	while(true)	
	{   //Get a frame from the input video.
		colourImage = cvQueryFrame(input);

		//If there are no more frames, jump out of the for.
		if( !colourImage )
		{
			break;
		}

		//If this is the first time, initialize the images.
		if(first)
		{
			difference = cvCloneImage(colourImage);
			temp = cvCloneImage(colourImage);
			cvConvertScale(colourImage, movingAverage, 1.0, 0.0);
			first = false;
		}
		//else, make a running average of the motion.
		else
		{
			cvRunningAvg(colourImage, movingAverage, 0.020, NULL);
		}
		cvShowImage("orginal", colourImage);
		//Convert the scale of the moving average.
		cvConvertScale(movingAverage,temp, 1.0, 0.0);

		//Minus the current frame from the moving average.
		cvAbsDiff(colourImage,temp,difference);

		cvShowImage("DifferenceFrame", difference);

		//Convert the image to grayscale.
		cvCvtColor(difference,greyImage,CV_RGB2GRAY);

		//Convert the image to black and white.
		cvThreshold(greyImage, greyImage, 70, 255, CV_THRESH_BINARY);
		roadPoint = 0; vehiclePoint = 0;
		for(int x = 0 ; x< imgSize.width ;x++){
			for(int y = 0 ; y < imgSize.height ; y++){
				unsigned char v = greyImage->imageData[imgSize.width*y +x];
				if(v == 255){
					vehiclePoint++;
					roadImage->imageData[imgSize.width*y +x] = v;
				}
			}
		}//end
		for(int x = 0 ; x< imgSize.width ;x++){
			for(int y = 0 ; y < imgSize.height ; y++){
				unsigned char v = roadImage->imageData[imgSize.width*y +x];
				if(v == 255)	roadPoint++;
			}
		}//end
		printf("vehicle		 = %f\n", vehiclePoint);
		printf("road		 = %f\n", roadPoint);
		printf("vehicle/road = %f\n", vehiclePoint/roadPoint);
		cvShowImage("Road", roadImage);
		//Dilate and erode to get people blobs
		cvDilate(greyImage, greyImage, 0, 18);
		cvErode(greyImage, greyImage, 0, 10);

		cvShowImage("DifferenceFrameAfterProcess", greyImage);
		cvWaitKey(1);
	}
	system("pause");




	return 0;
}